<template>
  <div class="settings-page">
    <!-- 用户信息 -->
    <van-cell-group>
      <van-cell title="头像" is-link @click="onChangeAvatar" class="avatar-cell">
        <template #value>
          <van-image :src="user.avatar" round width="50px" height="50px" />
        </template>
      </van-cell>
      <van-cell title="名称" is-link @click="onChangeName">
        <template #value>
          <span>{{ user.username }}</span>
        </template>
      </van-cell>
    </van-cell-group>

    <!-- 退出登录 -->
    <van-button type="danger" block round class="logout-button" @click="onLogout">
      退出登录
    </van-button>

    <!-- 修改名称弹窗 -->
    <van-dialog
      v-model:show="showNameDialog"
      title="修改名称"
      show-cancel-button
      confirm-button-text="保存"
      @confirm="saveName"
    >
      <van-field v-model="tempName" placeholder="请输入新的名称" />
    </van-dialog>

    <!-- 修改头像弹窗 -->
    <van-uploader v-model:file-list="avatarFileList" :after-read="afterReadAvatar" max-count="1" show-upload="false">
      <van-dialog
        v-model:show="showAvatarDialog"
        title="修改头像"
        show-cancel-button
        confirm-button-text="确定"
        @confirm="saveAvatar"
      >
        <van-image v-if="tempAvatar" :src="tempAvatar" width="100%" height="150px" />
        <div class="center-button">
          <el-upload
            ref="uploadRef"
            class="upload-demo"
            :limit="1"
            :action="uploadURL"
            :headers="headers"
            :data="uploadData"
            :auto-upload="false"
            :on-success="uploadSuccess"
            :on-error="uploadError"
          >
            <template #trigger>
              <el-button type="primary" class="photo-select">选择头像</el-button>
            </template>
            <div>
              <el-button type="success" @click="submitUpload()">上传头像</el-button>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                <p>限制上传1个文件，且旧文件会被新文件覆盖</p>
              </div>
            </template>
          </el-upload>
        </div>
      </van-dialog>
    </van-uploader>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { showToast, Dialog } from 'vant';
import useUser from '@/stores/user';
import useToken from '@/stores/token';
import { changeUserAvatar } from '@/api/'; // 假设有个 API 模块

const router = useRouter();

// 用户数据
const { user, updateUsername } = useUser();
const { removeToken } = useToken();
const { removeUser, updateUser } = useUser();

// 临时数据
const tempName = ref('');
const tempAvatar = ref('');
const avatarFileList = ref([]);
const uploadRef = ref()

// 弹窗控制
const showNameDialog = ref(false);
const showAvatarDialog = ref(false);
import { uploadPictureURL } from '@/api';
import notification from '@/utils/notification'
const { token } = useToken()

// 修改名称
const onChangeName = () => {
  tempName.value = user.username;
  showNameDialog.value = true;
};

// 保存新名称
const saveName = async () => {
  if (tempName.value.trim()) {
    await updateUsername(tempName.value);
    showNameDialog.value = false;
  } else {
    alert({ message: '名称不能为空！' });
  }
};

// 上传地址与相关参数
const uploadURL = uploadPictureURL() // 替换为你的后端接口
const headers = { jwt: token }
const uploadData = { type: 'user_avatar' }; // 上传类型



// 修改头像
const onChangeAvatar = () => {
  showAvatarDialog.value = true;
};

const submitUpload = () => {
  uploadRef.value.submit()
}

// 上传头像成功回调
const uploadSuccess = async (response) => {
  const { errno, errmsg, data } = response
  if( errno!==0){
    notification({
      message: errmsg,
      type: 'error'
    })
  }else{
    if(errmsg!==''){
      notification({
        message: errmsg,
        type: 'success'
      })
    }
    await changeUserAvatar({
      avatar: data.savepath
    })
    updateUser({
      avatar: data.url
    })
    uploadRef.value.clearFiles()
  }
};

// 上传头像失败回调
const uploadError = () => {
  showToast({ message: '上传失败，请重试', type: 'fail' });
};

// 保存头像
const saveAvatar = () => {
  if (!tempAvatar.value) {
    alert('请先选择头像！')
    return;
  }
  showAvatarDialog.value = false;
};

// 退出登录
const onLogout = () => {
  removeToken();
  removeUser();
  router.push({ name: 'user' });
  showToast({
    message: '退出成功',
    type: 'success',
  });
};
</script>

<style scoped>
.settings-page {
  padding: 16px;
  background-color: #f8f8f8; /* 这里修改为你想要的背景颜色 */
}

.avatar-cell {
  display: flex;
  align-items: center;
}

.logout-button {
  margin-top: 20px;
}

.center-button {
  display: flex;
  justify-content: center; /* 水平居中 */
  margin-top: 20px; /* 根据需要调整按钮的间距 */
}
</style>
